<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item label="分类" prop="categoryId" label-width="80px">
        <el-cascader
          v-model="dataForm.categoryPath"
          :options="options"
          @change="handleChange"
          placeholder="请选择分类"
          clearable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
        <el-select
          v-model="dataForm.courseId"
          placeholder="请选择课程"
          clearable
        >
          <el-option
            v-for="item in courses"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="dataForm.type" placeholder="请选择类型" clearable>
          <el-option
            v-for="item in types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="录入人">
        <el-input v-model="dataForm.input" placeholder="录入人" clearable>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-form
      ref="testPaper"
      :inline="true"
      :model="testPaper"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item prop="name" label="试卷名称">
        <el-input
          v-model="testPaper.name"
          style="width: 205px;"
          placeholder="试卷名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createTestPaper">立即创建</el-button>
      </el-form-item>
      <el-form-item :currentData="currentData" class="red">
        目前选中 {{ currentData.count }} 条题目，总分为
        {{ currentData.totalScore }} 分。
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"
      row-key="id"
      stripe
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="categoryName"
        header-align="center"
        align="center"
        label="分类"
      >
      </el-table-column>
      <el-table-column
        prop="courseName"
        header-align="center"
        align="center"
        label="课程"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        header-align="center"
        align="center"
        label="类型"
      >
      </el-table-column>
      <el-table-column
        prop="question"
        header-align="center"
        align="center"
        label="题目"
      >
        <template slot-scope="scope">
          <p v-html="scope.row.question"></p>
        </template>
      </el-table-column>
      <el-table-column
        prop="answer"
        header-align="center"
        align="center"
        label="答案"
      >
        <template slot-scope="scope">
          <p v-html="scope.row.answer"></p>
        </template>
      </el-table-column>
      <el-table-column
        prop="score"
        header-align="center"
        align="center"
        label="分数"
      >
      </el-table-column>
      <el-table-column
        prop="input"
        header-align="center"
        align="center"
        label="录入人"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="录入时间"
      >
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[50, 100, 1000, 10000, 100000]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rules: {
        name: [
          { required: true, message: "请输入试卷名称", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (this.currentData.count <= 0) {
                callback(new Error("请选择试题"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      testPaper: {
        id: 0,
        name: "",
        num: "",
        score: "",
        creator: "",
        createTime: "",
        updateTime: "",
        testPaperSons: []
      },
      currentData: {
        count: 0,
        totalScore: 0
      },
      dataForm: {
        categoryPath: [],
        categoryId: "",
        courseId: "",
        type: "",
        input: ""
      },
      options: [],
      types: [
        {
          value: "选择",
          label: "选择"
        },
        {
          value: "填空",
          label: "填空"
        },
        {
          value: "问答",
          label: "问答"
        }
      ],
      courses: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    };
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/web/testquestion/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          categoryId: this.dataForm.categoryId,
          courseId: this.dataForm.courseId,
          type: this.dataForm.type,
          input: this.dataForm.input
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
      // 获取分类信息
      this.$http({
        url: this.$http.adornUrl(`/web/category/get/category/list`),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          let res = data.data;
          let d = [];
          res.forEach(item => {
            let model = {};
            model.label = item.name;
            model.value = item.id;
            if (item.children.length > 0) {
              this.formatCategoryPath(model, item.children);
            }
            d.push(model);
          });
          this.options = d;
        }
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
      this.currentData.count = this.dataListSelections.length;
      let totalScore = 0;
      this.dataListSelections.forEach(item => {
        totalScore += item.score;
      });
      this.currentData.totalScore = totalScore;
      this.testPaper.testPaperSons = this.dataListSelections;
    },
    formatCategoryPath(parent, children) {
      let d = [];
      children.forEach(item => {
        let model = {};
        model.label = item.name;
        model.value = item.id;
        if (item.children.length > 0) {
          this.formatCategoryPath(model, item.children);
        }
        d.push(model);
      });
      parent.children = d;
    },
    handleChange(value) {
      this.dataForm.categoryId = value[value.length - 1];
      this.dataForm.courseId = "";
      // 获取课程信息
      this.courses = [];
      let categoryId = this.dataForm.categoryId;
      if (categoryId != null && categoryId !== "" && categoryId !== 0) {
        this.$http({
          url: this.$http.adornUrl(`/web/course/get/list/by/${categoryId}`),
          method: "get"
        }).then(({ data }) => {
          let courses = data.data;

          courses.forEach(item => {
            let course = {
              value: item.id,
              label: item.name
            };
            this.courses.push(course);
          });
        });
      }
    },
    createTestPaper() {
      this.$refs["testPaper"].validate(valid => {
        if (valid) {
          this.testPaper.score = this.currentData.totalScore;
          this.testPaper.num = this.currentData.count;
          console.log("this.testPaper :>> ", this.testPaper);
          this.$http({
            url: this.$http.adornUrl(`/web/testpaper/save`),
            method: "post",
            data: this.$http.adornData({
              name: this.testPaper.name,
              num: this.testPaper.num,
              score: this.testPaper.score,
              testPaperSons: this.testPaper.testPaperSons
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>

<style>
.red {
  color: red;
}
</style>
